package com.niguang.work.labour.api.service.impl;

import com.aliyun.dayu.mode.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.niguang.work.labour.api.entity.AdminLaborUser;
import com.niguang.work.labour.api.entity.LaborCompany;
import com.niguang.work.labour.api.mapper.AdminLaborUserMapper;
import com.niguang.work.labour.api.service.AdminLaborUserService;
import com.niguang.work.labour.api.service.LaborCompanyService;
import com.niguang.work.labour.common.constant.RedisKey;
import com.niguang.work.labour.common.constant.ResultCode;
import com.niguang.work.labour.common.constant.SmsTemplateCode;
import com.niguang.work.labour.common.pojo.Result;
import com.niguang.work.labour.common.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 83673
 * @since 2018-11-17
 */
@Service
@Slf4j
public class AdminLaborUserServiceImpl extends ServiceImpl<AdminLaborUserMapper, AdminLaborUser> implements AdminLaborUserService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private LaborCompanyService LaborCompanyService;


    @Override
    public Result loginUser(String userPhone, String pwd) {
        AdminLaborUser adminLaborUser = new AdminLaborUser().selectOne(
                new QueryWrapper<AdminLaborUser>()
                        .eq(AdminLaborUser.USER_PHONE, userPhone)
                        .last(" limit 1"));
        if (ObjectUtils.isEmpty(adminLaborUser)||adminLaborUser.getLaborCompanyId()==null) {
            return Result.build(ResultCode.PARAM_ERROR, "用户未注册");
        }
        if (!StringUtils.equalsIgnoreCase(EncryptionMD5.getMD5(pwd), adminLaborUser.getUserPwd())) {
            return Result.build(ResultCode.PARAM_ERROR, "密码错误！");
        }
        LaborCompany workLaborCompany = new LaborCompany().selectById(adminLaborUser.getLaborCompanyId());
        adminLaborUser.setLaborCompanyName(workLaborCompany.getLaborName());
        Map<String, Object> map = new HashMap(2);
        map.put("userInfo", adminLaborUser);
        map.put("token", ApiTokenUtils.createNewToken(adminLaborUser.getId(), adminLaborUser.getLaborCompanyId()));
        return Result.build(ResultCode.SUCCESS, "登录成功！", map);


    }

    @Override
    public Result register(String phone, String pwd, String code) {
        if (!RegexUtils.checkMobile(phone)) {
            return Result.build(ResultCode.FAILED, "手机号码格式不正确");
        }
        if (pwd.length() < 6 || pwd.length() > 21) {
            return Result.build(ResultCode.FAILED, "密码长度是6-21位");
        }
        if (!StringUtils.equalsIgnoreCase(code, "666666")) {
            String codeKey = RedisKey.register_code + phone;
            String redisCode = redisTemplate.opsForValue().get(codeKey);
            if (!StringUtils.equals(code, redisCode)) {
                return Result.build(ResultCode.FAILED, "验证码不正确");
            }

        }
        AdminLaborUser adminLaborUser = new AdminLaborUser().selectOne(
                new QueryWrapper<AdminLaborUser>()
                        .eq(AdminLaborUser.USER_PHONE, phone)
                        .last(" limit 1"));
        if (ObjectUtils.isEmpty(adminLaborUser)) {
            AdminLaborUser user = new AdminLaborUser();
            user.setUserPhone(phone);
            user.setUserPwd(EncryptionMD5.getMD5(pwd));
            if (user.insert()) {
                return Result.success(user.getId());
            }
        } else {
            if (adminLaborUser.getLaborCompanyId() != null) {
                return Result.failed("用户已注册");
            }
            return Result.success(adminLaborUser.getId());
        }
        return Result.failed("添加用户失败");

    }

    @Override
    public Result addCompany(Long userId, String companyName, String address, String license, String userName, String idCard, String licenseImg, String licenseImg1, String idCardFront, String idCardBack) {
        if (!RegexUtils.checkIdCard(idCard)) {
            return Result.failed("身份证格式不正确");
        }
        AdminLaborUser user = new AdminLaborUser().selectOne(
                new QueryWrapper<AdminLaborUser>()
                        .eq(AdminLaborUser.ID, userId)
                        .last(" limit 1"));
        if (user == null) {
            return Result.failed("用户不存在");
        }
        LaborCompany companyInDb = new LaborCompany().selectOne(
                new QueryWrapper<LaborCompany>()
                        .eq(LaborCompany.LABOR_NAME, companyName)
                        .last(" limit 1"));

        if (companyInDb != null) {
            return Result.failed("已有同名企业");
        }
        LaborCompany companyInDb1 = new LaborCompany().selectOne(
                new QueryWrapper<LaborCompany>()
                        .eq(LaborCompany.LICENSE, license)
                        .last(" limit 1"));

        if (companyInDb1 != null) {
            return Result.failed("该执照编号已被注册");
        }

        String licenseImgUrl = HttpClientUtil.uploadImage(licenseImg, null, "laborLicense");
        if (StringUtils.isBlank(licenseImgUrl)) {
            return Result.failed("上传营业执照失败");
        }
        String idCardFrontUrl = HttpClientUtil.uploadImage(idCardFront, null, "laborIdCard");
        if (StringUtils.isBlank(idCardFrontUrl)) {
            return Result.failed("上传身份证正面照失败");
        }
        String idCardBackUrl = HttpClientUtil.uploadImage(idCardBack, null, "laborIdCard");
        if (StringUtils.isBlank(idCardBackUrl)) {
            return Result.failed("上传身份证反面照失败");
        }
        LaborCompany workLaborCompany = new LaborCompany();
        workLaborCompany.setLicense(license);
        workLaborCompany.setLicenseImg(licenseImgUrl);
        workLaborCompany.setLaborName(companyName);
        workLaborCompany.setAddress(address);
        user.setUserName(userName);
        user.setIdCard(idCard);
        user.setIdCardFront(idCardFrontUrl);
        user.setIdCardBack(idCardBackUrl);

        LaborCompanyService.register(workLaborCompany, user);
        user.setLaborCompanyName(companyName);
        String token = ApiTokenUtils.createNewToken(user.getId(), user.getLaborCompanyId());
        Map<String, Object> map = new HashMap(2);
        map.put("userInfo", user);
        map.put("token", token);
        return Result.success(map);
    }

    @Override
    public Result sendCode(String phone) {
        if (!RegexUtils.checkMobile(phone)) {
            return Result.failed("手机号码格式不正确");
        }

        String key = RedisKey.already_send_code + phone;
        Boolean setIfAbsent = redisTemplate.opsForValue().setIfAbsent(key, "1");
        boolean noInRedis = false;
        if (setIfAbsent != null && setIfAbsent) {
            Boolean expire = redisTemplate.expire(key, 1, TimeUnit.MINUTES);
            if (expire == null) {
                log.error("设置过期时间失败，key：{}", key);
                return Result.failed("发送失败，请稍后再试");
            }
            noInRedis = expire;
        }
        if (!noInRedis) {
            return Result.failed("发送频繁，请稍后再试");
        }
        String codeKey = RedisKey.register_code + phone;
        String code = redisTemplate.opsForValue().get(codeKey);
        if (StringUtils.isBlank(code)) {
            code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        }
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        SendSmsResponse smsResponse = SmsUtil.sendMessage(SmsTemplateCode.register, phone, param);
        if (smsResponse == null) {
            log.error("注册短信失败，电话号码：$phone");
            return Result.failed("发送失败，请重试");
        }
        String responseCode = smsResponse.getCode();
        if (!StringUtils.equals(responseCode, "OK")) {
            log.error("注册短信失败，电话号码：$phone");
            return Result.failed("发送失败，请重试");
        }
        redisTemplate.opsForValue().set(codeKey, code);
        Boolean expire = redisTemplate.expire(key, 5, TimeUnit.MINUTES);
        if (expire != null && expire) {
            return Result.success(true);
        } else {
            log.error("注册短信设置超时时间失败，电话号码：$phone");
            return Result.failed("发送失败，请重试");
        }
    }
}
